/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.pz.util;

import com.pz.net.master.Client;
import com.pz.net.Command;
import com.pz.net.master.MasterServer;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;

/**
 *
 * @author jannek
 */
public abstract class ByteBufferHelper {
    
    public static void put(byte[] data, ByteBuffer buffer) {
        byte length = (byte) ((data.length > 127) ? 127 : data.length);
        buffer.put(length);
        buffer.put(data, 0, length);
    }

    public static void put(String message, ByteBuffer buffer) {
        put(message.getBytes(), buffer);
    }

    public static void put(Command command, ByteBuffer buffer) {
        buffer.put((byte) command.ordinal());
    }

    public static void put(SocketAddress address, ByteBuffer buffer) {
        InetSocketAddress inet = (InetSocketAddress) address;
        put(inet.getHostName().getBytes(), buffer);
        buffer.putInt(inet.getPort());
    }

    public static void put(Client client, ByteBuffer buffer) {
        buffer.putInt(client.id);
        put(client.getAddress(), buffer);
    }

    public static byte[] getBytes(ByteBuffer buffer) {
        byte[] data = new byte[buffer.get()];
        buffer.get(data);
        return data;
    }

    public static String getString(ByteBuffer buffer) {
        return new String(getBytes(buffer));
    }

    public static Command getCommand(ByteBuffer buffer) {
        return Command.values()[buffer.get()];
    }

    public static SocketAddress getAddress(ByteBuffer buffer) {
        return new InetSocketAddress(getString(buffer), buffer.getInt());
    }
}
